package com.ccit.course.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.exception.GymException;
import com.ccit.common.exception.fileUpload.FileEmptyException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.UploadUtil;
import com.ccit.course.service.CourseService;
import com.ccit.model.Course;
import com.ccit.model.Goods;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "课程管理")
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private UploadUtil uploadUtil;

    @Autowired
    private CourseService courseService;

    @Autowired
    private RedisUtils redisUtils;

    final String port = "8085";


    //    @Cacheable(value = "course", keyGenerator = "KeyGenerator")
    @ApiOperation(value = "查询所有课程")
    @GetMapping("/listAll")
    public Result listAll() {

        List<Course> list ;
        boolean has = redisUtils.hasKey("courseList");
        if (has){
             list = (List<Course>)redisUtils.get("courseList");
        }else {
             list = courseService.list();
             redisUtils.set("courseList",list,60*120*24*7);
        }
        return Result.ok(list);
    }


    @ApiOperation(value = "根据id查询课程")
    @GetMapping("/getCourseById/{id}")
    public Result getCourseById(@PathVariable String id) {
        Course course;
        String key = "course:"+id;
        boolean has = redisUtils.hasKey(key);
        if (has){
            course = (Course)redisUtils.get(key);
        }else {
            course = courseService.getById(id);
            redisUtils.set(key,course,60*120*24*7);
        }

        if (course == null){
            throw new GymException(202,"无此课程id存在");
        }else return Result.ok();

    }


    @ApiOperation(value = "分页查询课程")
    @GetMapping("/getCourseByPage/{current}/{size}")
    public Result getCourseByPage(@PathVariable Integer current, @PathVariable Integer size) {
        Page<Course> page = new Page<>(current, size);
        Page<Course> coursePage;
        String key = "coursePage:"+current+":"+size;
        boolean has = redisUtils.hasKey(key);
        if (has){
             coursePage  = (Page<Course>)redisUtils.get(key);
        }else {
             coursePage = courseService.page(page);
             redisUtils.set(key,coursePage,60*120*24*7);
        }
        return Result.ok(coursePage);
    }


    @ApiOperation(value = "新增课程")
    @PostMapping("/saveNewCourse")
    public Result upload(@RequestPart MultipartFile file, @RequestPart String courseStr) {
        if (file==null){
            throw new FileEmptyException();
        }
        String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
        Map<String, String> map = new HashMap<>();
        map.put("pathPrefix", pathPrefix);
        map.put("src", "course");
        String fileName = uploadUtil.saveFile(file, map);

        JSONObject object = JSON.parseObject(courseStr);

        Course course = new Course();
        course.setName(object.getString("name"));
        course.setCourseTimes(object.getInteger("course_times"));
        course.setPrice(object.getDouble("price"));
        course.setImgUrl("http://localhost:" + port + "/course/img/" + fileName);
        boolean result = courseService.save(course);
        if (result)
        {
            redisUtils.deleteRedisKeys("courseList");
            redisUtils.deleteRedisKeys("course");
            redisUtils.deleteRedisKeys("coursePage");
            return Result.ok("添加成功");
        }
        else
            return Result.fail(null).message("添加失败了");
    }

    @ApiOperation("修改课程信息课程")
    @PutMapping("/updateCourseInfo")
    public Result updateCourseInfo(@RequestParam(required = false) MultipartFile file, @RequestPart String courseStr) {

        JSONObject object = JSON.parseObject(courseStr);
        Course course = courseService.getById(object.getLong("id"));
        course.setPrice(object.getDouble("price"));
        course.setCourseTimes(object.getInteger("courseTimes"));
        course.setName(object.getString("name"));

        if (file != null) {
            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();

            int lastIndexOf = course.getImgUrl().lastIndexOf("/");
            String img_path = course.getImgUrl().substring(lastIndexOf + 1, course.getImgUrl().length());

            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "course");
            //旧文件路径
            img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;

            //删除旧文件
            File OldFile = new File(img_path);
            if (OldFile.exists()) {
                if (OldFile.delete()) {
                    String fileName = uploadUtil.saveFile(file, map);
                    course.setImgUrl("http://localhost:" + port + "/course/img/" + fileName);
                } else {
                    return Result.fail().message("删除失败");
                }
            } else {
                String fileName = uploadUtil.saveFile(file, map);
                course.setImgUrl("http://localhost:" + port + "/course/img/" + fileName);
            }

        }

        boolean result = courseService.updateById(course);
        if (result){
            redisUtils.deleteRedisKeys("courseList");
            redisUtils.deleteRedisKeys("course");
            redisUtils.deleteRedisKeys("coursePage");
            return Result.ok("修改成功");
        }
        else
            return Result.fail().message("修改失败");
    }

    //    @CacheEvict(value = "course", keyGenerator = "KeyGenerator")
    @ApiOperation("删除课程")
    @PutMapping("/removeCourseById/{id}")
    public Result removeCourseById(@PathVariable Integer id) {
        boolean result = courseService.removeById(id);
        if (result){
            redisUtils.deleteRedisKeys("courseList");
            redisUtils.deleteRedisKeys("course");
            redisUtils.deleteRedisKeys("coursePage");
            return Result.ok("删除成功");
        }
        else
            return Result.fail("删除失败");
    }



}
